package com.cats.bi.sqltool.function;

import com.cats.bi.sqltool.basic.AbstractSearchable;
import com.cats.bi.sqltool.basic.Column;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

/**
 * @author duxiaobo
 * @date 2021/9/23:40 下午
 */
@Setter
@Getter
public class Lag extends Column {

    private String partition;
    private String order;

    public Lag(String name) {
        super(name);
    }

    public Lag(String table, String name) {
        super(table, name);
    }

    public Lag(AbstractSearchable table, String tableAlias, String name) {
        super(table, tableAlias, name);
    }

    public Lag(AbstractSearchable table, String tableAlias, String name, String partition) {
        super(table, tableAlias, name);
        this.partition = partition;
    }

    public Lag(AbstractSearchable table, String tableAlias, String name, String partition, String order) {
        super(table, tableAlias, name);
        this.partition = partition;
        this.order = order;
    }

    @Override
    public void toSql(StringBuilder sb) {
        sb.append("LAG(");
        super.toSql(sb);
        sb.append(")")
                .append(" OVER( ");
        if (!StringUtils.isBlank(partition)) {
            sb.append(" PARTITION BY ")
                    .append(partition);
        }

        if (!StringUtils.isBlank(order)) {
            sb.append(" ORDER BY ")
                    .append(order);
        }
        sb.append(")");
    }
}
